package com.test.webtest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.webtest.entity.Site;
import com.test.webtest.exception.BaseException;
import com.test.webtest.mapper.SiteMapper;
import com.test.webtest.service.SiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description SiteServiceImpl
 * @Author jiangzhenghao
 * @Date 2025-05-16  20:31
 */
@Service
public class SiteServiceImpl extends ServiceImpl<SiteMapper, Site> implements SiteService {

    @Autowired
    private SiteMapper siteMapper;

    @Override
    public Page<Site> pageQuery(Integer page, Integer pageSize) {

        Page<Site> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<Site> queryWrapper = new LambdaQueryWrapper<>();
        // 可根据销量，价格，访问量排序
        queryWrapper.orderByDesc(Site::getSales, Site::getPrice, Site::getViews);
        Page<Site> resultPage = siteMapper.selectPage(pageParam, queryWrapper);
        return resultPage;
    }

    @Override
    public Site detail(Integer id) {
        Site site = getById(id);
        if (site == null) {
            throw new BaseException("站点不存在");
        }

        // 每次访问都加对应访问量
        Integer views = site.getViews();
        if (views == null || views == 0) {
            site.setViews(1);
        } else {
            site.setViews(views + 1);
        }
        updateById(site);

        return site;
    }
}
